import type { App } from 'vue'


const map = new WeakMap<Element, ResizeFn>()

const ob = new ResizeObserver((entries) => {
    entries.forEach((item) => {
        const fn = map.get(item.target)
        const [{ blockSize, inlineSize }] = item.borderBoxSize

        fn?.({
            width: blockSize,
            height: inlineSize,
            size: item
        })
    })
})

/**
 * 尺寸变化时，回调大小给你
 * @param { ResizeFn } value
 */
export function resize(app: App<HTMLElement>) {
    app.directive('resize', {
        mounted(el, { value }) {
            map.set(el, value)
            ob.observe(el)
        },
        beforeUnmount(el) {
            map.delete(el)
            ob.unobserve(el)
        }
    })
}


export type ResizeFn = (data: {
    size: ResizeObserverEntry
    width: number
    height: number
}) => void
